package win.smartown.android.scrollPager

import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.text.TextUtils
import android.util.AttributeSet
import android.view.MotionEvent
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient

/**
 * Created by smartown on 2017/6/22 10:44.
 * Description:
 */
class ScrollableWebView : WebView, ScrollState {

    private var content: String = ""
    /**
     *1:url 2.html
     */
    private var contentType: Int = 0
    private var contentShown = false

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, privateBrowsing: Boolean) : super(context, attrs, defStyleAttr, privateBrowsing) {
        init()
    }

    fun init() {
        settings.javaScriptEnabled = true
        setWebViewClient(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(url)
                return true
            }
        })
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
    }

    fun setUrlContent(url: String) {
        content = url
        contentType = 1
        contentShown = false
    }

    fun setHtmlContent(html: String) {
        content = html
        contentType = 2
        contentShown = false
    }

    fun showContent() {
        if (!contentShown) {
            contentShown = true
            if (!TextUtils.isEmpty(content)) {
                when (contentType) {
                    1 -> loadUrl(content)
                    2 -> loadData(content, "text/html; charset=utf-8", "utf-8")
                }
            }
        }
    }

    override fun atTop(): Boolean {
        return scrollY == 0
    }

    override fun atBottom(): Boolean {
        return (scrollY + height) >= contentHeight
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        onScroll()
        return super.onTouchEvent(event)
    }

    override fun onScroll() {
        if (parent is OnPagerScrollListener) {
            (parent as OnPagerScrollListener).onPagerScroll(this, scrollY)
        }
    }

}